package netty.c2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.nio.charset.Charset;

public class EventLoopServer {
    static Logger logger = LogManager.getLogger("mylog");

    public static void main(String[] args) {
        EventLoopGroup group = new DefaultEventLoopGroup();

        new ServerBootstrap()
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {

                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                // super.channelRead(ctx, msg);
                                ByteBuf buf = (ByteBuf) msg;
                                logger.debug(buf.toString(Charset.defaultCharset()));
                                ctx.fireChannelRead(msg); // 传递给下一个 handler
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                logger.debug("exceptionCaught");
                             //   Channel channel = ctx.channel();
                                //……
                              //  if(channel.isActive())ctx.close();
                            }
                        }); /* .addLast(group, "handler2", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                logger.debug(buf.toString(Charset.defaultCharset()));
                            }
                        } );  */

                    }
                })
                .bind(8080);


    }
}
